package com.bhs.sansonglogistics.ui.order;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.OrderGoodsDataBean;
import com.bhs.sansonglogistics.bean.WaybillBean;
import com.bhs.sansonglogistics.bean.WaybillDataBean;
import com.bhs.sansonglogistics.bean.event.ScreenEvent;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.ScreenDialog;
import com.bhs.sansonglogistics.dialog.ScreenListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.HistoryAdapter;
import com.bhs.sansonglogistics.ui.adapter.OrderGoodsAdapter;
import com.bhs.sansonglogistics.ui.adapter.WaybillAdapter;
import com.bhs.sansonglogistics.ui.waybill.AdjustWaybillActivity;
import com.bhs.sansonglogistics.ui.waybill.WaybillDetailsActivity;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.AutoLineFeedLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 订单搜索
 */
public class OrderSearchActivity extends BaseActivity implements NetCallBack, View.OnClickListener {

    private EditText mEtSearch;
    private TextView mTvHistorySearch;
    private TextView mTvClear;
    private RecyclerView mRvHistorySearch;
    private RecyclerView mRvWaybill;
    private int page = 1;
    private OrderGoodsAdapter orderGoodsAdapter;
    private String[] historyArray;
    private String historySearch;
    private LinkedList<String> HistoryList = new LinkedList<>();
    private HistoryAdapter historyAdapter;
    private ConstraintLayout mClHistorySearch;
    private OrderOperation orderOperation;
    private LinearLayout mLlSearch;
    private TextView mTvTitle;
    private String startTime, endTime;

    @Override
    public int initLayout() {
        return R.layout.activity_order_search;
    }

    @Override
    public void initView() {
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        mEtSearch = findViewById(R.id.et_search);
        mTvHistorySearch = findViewById(R.id.tv_history_search);
        mTvClear = findViewById(R.id.tv_clear);
        mTvClear.setOnClickListener(this);
        mRvHistorySearch = findViewById(R.id.rv_history_search);
        mRvWaybill = findViewById(R.id.rv_waybill);
        mClHistorySearch = findViewById(R.id.cl_history_search);
        mLlSearch = findViewById(R.id.ll_search);
        mTvTitle = findViewById(R.id.tv_title);
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 1;
                    loadData(mEtSearch.getText().toString());
                    search();
                    return true;
                }
                return false;
            }
        });
        TextView mTvDressingScreening = findViewById(R.id.tv_dressing_screening);
        mTvDressingScreening.setOnClickListener(this);
        historySearch = SharedPreferencesUtils.getString(this, "HistorySearch", null);
        if (historySearch != null) {
            historyArray = historySearch.split(",");
            if (historyArray.length > 30) {
                StringBuilder stringBuffer = new StringBuilder(historyArray[0]);
                for (int i = 1; i < 30; i++) {
                    stringBuffer.append(",");
                    stringBuffer.append(historyArray[i]);
                }
                SharedPreferencesUtils.saveString(this, "HistorySearch", stringBuffer.toString());
            }
        }

        if (historyArray != null) {
            HistoryList.addAll(Arrays.asList(historyArray));
        }
        historyAdapter = new HistoryAdapter(HistoryList);
        mRvHistorySearch.setAdapter(historyAdapter);
        mRvHistorySearch.setLayoutManager(new AutoLineFeedLayoutManager());
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                loadData(HistoryList.get(position));
            }
        });


    }

    private Map<String, String> parameters = new ArrayMap<>();

    private void loadData(String search_key) {
        parameters.put("search_key", search_key);
        parameters.put("page", String.valueOf(page));
        if (!TextUtils.isEmpty(startTime)) {
            parameters.put("start_time", startTime);
            parameters.put("end_time", endTime);
            parameters.put("status", "5,7,9,11,15,20");
        }
        networkRequest(netApi.getOrderList2(parameters), this);
    }

    @Override
    public void initData() {
        orderOperation = new OrderOperation(this);
        orderGoodsAdapter = new OrderGoodsAdapter(1);
        mRvWaybill.setAdapter(orderGoodsAdapter);
        mRvWaybill.setLayoutManager(new LinearLayoutManager(mActivity));
        orderGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderGoodsBean data = (OrderGoodsBean) adapter.getData().get(position);
                startActivity(new Intent(mActivity, OrderDetailsActivity.class)
                        .putExtra("deliver_sn", data.getDeliver_sn()));
            }
        });

        orderOperation.operation(orderGoodsAdapter);
        orderOperation.setMyClickListener(new MyClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                loadData(mEtSearch.getText().toString());
            }
        });
        if (!TextUtils.isEmpty(startTime)) {
            mClHistorySearch.setVisibility(View.GONE);
            mLlSearch.setVisibility(View.GONE);
            mTvTitle.setText("订单明细");
            loadData("");
            orderGoodsAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    page++;
                    loadData("");
                }
            }, mRvWaybill);

        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        loadingPopupDismiss();
        OrderGoodsDataBean dataBean = new Gson().fromJson(json, OrderGoodsDataBean.class);
        if (dataBean.isStatus()) {
            if (page == 1) {
                orderGoodsAdapter.setNewData(dataBean.getData().getList());
            } else {
                orderGoodsAdapter.loadMoreComplete();
                orderGoodsAdapter.addData(dataBean.getData().getList());
            }
            if (orderGoodsAdapter.getData().size() >= dataBean.getData().getTotal_count()) {
                orderGoodsAdapter.loadMoreEnd();
            }
            if (!MyUtils.isEmpty(dataBean.getData().getList())) {
                mClHistorySearch.setVisibility(View.GONE);
            } else {
                if (TextUtils.isEmpty(startTime)) {
                    mClHistorySearch.setVisibility(View.VISIBLE);
                }
            }
        } else {
            ToastUtil.show(dataBean.getMsg());
        }

    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }


    ScreenDialog screenDialog;

    private void bottomSelect() {
        if (screenDialog == null) {
            screenDialog = new ScreenDialog(mActivity);
            screenDialog.setMyClickListener(new ScreenListener() {
                @Override
                public void onClick(ScreenEvent event) {
                    page = 1;
                    parameters.put("start_time", event.getStart());
                    parameters.put("end_time", event.getEnd());
                    parameters.put("line_id", event.getLineId());
                    if (!TextUtils.isEmpty(event.getStatus())) {
                        if (event.getStatus().equals("0")) {
                            parameters.put("pay_status", "0");
                        } else if (event.getStatus().equals("101")) {
                            parameters.put("with_receipt", "2");
                        } else {
                            parameters.put("status", event.getStatus());
                        }
                    }
                    parameters.put("order_type", "");
                    parameters.put("deliver_type", "");
                    parameters.put("is_yuyue", "");
                    if (event.getType().equals("极速")) {
                        parameters.put("order_type", "2");
                    }
                    if (event.getType().equals("指派")) {
                        parameters.put("order_type", "1");
                    }

                    if (event.getType().equals("快运")) {
                        parameters.put("deliver_type", "2");
                    }
                    if (event.getType().equals("普运")) {
                        parameters.put("deliver_type", "1");
                    }
                    if (event.getType().equals("实时单")) {
                        parameters.put("is_yuyue", "0");
                    }
                    if (event.getType().equals("预约单")) {
                        parameters.put("is_yuyue", "1");
                    }
                    loadData("");
                }
            });
            screenDialog.show();
        } else {
            screenDialog.show();
        }


    }

    @SuppressLint("NotifyDataSetChanged")
    private void search() {
        String searchContext = mEtSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(searchContext)) {
            boolean isEqual = false;
            for (String s : HistoryList) {
                if (s.equals(searchContext)) {
                    isEqual = true;
                    break;
                }
            }
            if (isEqual) {
                return;
            }
            if (historySearch == null) {
                historySearch = searchContext;
            } else {
                historySearch = searchContext + "," + historySearch;
            }
            SharedPreferencesUtils.saveString(this, "HistorySearch", historySearch);
            HistoryList.addFirst(searchContext);
            historyAdapter.notifyDataSetChanged();
        }

    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_dressing_screening) {
            bottomSelect();
        } else if (view.getId() == R.id.tv_clear) {
            SharedPreferencesUtils.clear(this, "HistorySearch");
            HistoryList.clear();
            historyAdapter.notifyDataSetChanged();
        }
    }
}